package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

const URLPrefix = "gdbc://mysql://"

type Config struct {
	Datasource Datasource `json:"datasource"`
}
type Datasource struct {
	TableName string `json:"table_name"`
	URL       string `json:"url"`
	Username  string `json:"username"`
	Password  string `json:"password"`
}

func convertToDNS(url, username, password string) (string, error) {
	trimUrl := strings.TrimPrefix(url, URLPrefix)
	parts := strings.Split(trimUrl, "/")
	if len(parts) != 2 {
		return "", fmt.Errorf("invalid mysql url")
	}
	return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, parts[0], parts[1]), nil
}
func (m *Config) InitDB() (*gorm.DB, error) {
	if !strings.HasPrefix(m.Datasource.URL, URLPrefix) {
		return nil, fmt.Errorf("unsupported database type or invalid DNS format")
	}
	dns, err := convertToDNS(m.Datasource.URL, m.Datasource.Username, m.Datasource.Password)
	if err != nil {
		return nil, err
	}
	db, err := gorm.Open(mysql.Open(dns), &gorm.Config{})
	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %w", err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		return nil, fmt.Errorf("failed to get database instance: %w", err)
	}

	// 设置连接池参数
	sqlDB.SetMaxIdleConns(20)
	sqlDB.SetMaxOpenConns(200)
	sqlDB.SetConnMaxLifetime(30 * time.Minute)
	sqlDB.SetConnMaxIdleTime(10 * time.Minute)

	return db, nil
}
